﻿using NetMQ;
using NetMQ.Sockets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace MebApp.Launcher
{
    public enum ShortcutLaunchFlag
    {
        None,
        CmdSent,
        NoResponse
    }
    public class ShortcutLaunchClient
    {
        //发个消息给已存在的进程，让其启动一个app，然后本进程退出
        public static ShortcutLaunchFlag LaunchByArguments(string arguments, out Guid appId)
        {
            //mebapp://runapp/guid
            appId = Guid.Empty;
            var regex = new Regex("^mebapp://runapp/(\\w{8}-(\\w{4}-){3}\\w{12})$");
            Match match = null;
            if ((match = regex.Match(arguments)).Success && Guid.TryParse(match.Groups[1].Value, out appId))
            {
                using (NetMQ.NetMQSocket socket = new RequestSocket("tcp://127.0.0.1:51120"))
                {
                    socket.SendFrame("runapp", true);
                    socket.SendFrame(appId.ToString());
                    var frameString = "";
                    return socket.TryReceiveFrameString(TimeSpan.FromSeconds(1), out frameString) ? ShortcutLaunchFlag.CmdSent : ShortcutLaunchFlag.NoResponse;
                }
            }
            return ShortcutLaunchFlag.None;
        }
    }
    public class ShortcutLaunchListener
    {
        public static Action<Guid> ListenAction;
        public static void StartListen(Action<Guid> callback)
        {
            ListenAction = callback;
            var thread = new Thread(ListenThread) { IsBackground = true };
            thread.Start();
        }
        static void ListenThread()
        {
            NetMQ.NetMQSocket socket = new ResponseSocket();
            socket.Bind("tcp://127.0.0.1:51120");
            while (true)
            {
                var command = socket.ReceiveFrameString();
                if (command == "runapp")
                {
                    var appId = socket.ReceiveFrameString();
                    var value = Guid.Parse(appId);
                    ListenAction?.BeginInvoke(value, null, null);
                    socket.SignalOK();
                }
            }
        }
    }
}
